package cc.vv.btpartyjob.partymanager.fragment

import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import cc.vv.baselibrary.bean.base.BaseResponseObj
import cc.vv.baselibrary.http.BaseHttpRequest
import cc.vv.baselibrary.util.LKToastUtil
import cc.vv.baselibrary.util.UserInfoManageUtil
import cc.vv.baselibrary.util.VideoPlayerUtils
import cc.vv.baselibrary.view.imgselector.ImageSelector
import cc.vv.btpartyjob.jnimodule.api.JniModuleAPI
import cc.vv.btpartyjob.jnimodule.moudel.resp.FileUpResponseObj
import cc.vv.btpartyjob.jnimodule.server.ResourceChooseServer
import cc.vv.btpartyjob.partymanager.R
import cc.vv.btpartyjob.partymanager.api.PartyManagerAPI
import cc.vv.btpartyjob.partymanager.delegate.ManagerBaseBinder
import cc.vv.btpartyjob.partymanager.delegate.WorkInFragmentDelegate
import cc.vv.btpartyjob.partymanager.inter.AddWorkIdInterface
import cc.vv.btpartyjob.partymanager.inter.LookBigPicFileInterface
import cc.vv.btpartyjob.partymanager.moudel.bean.AddQianDaoObj
import cc.vv.btpartyjob.partymanager.moudel.resp.AddQianDaoResponseObj
import cc.vv.btpartyjob.partymanager.moudel.resp.DiYiShuJiInfoResponseObj
import cc.vv.btpartyjob.partymanager.moudel.resp.QianDaoResponseObj
import cc.vv.btpartyjob.partymanager.server.PartyManagerServer
import cc.vv.lkbasecomponent.http.lib.setting.Settings
import cc.vv.lklibrary.http.base.okhttpfactory.plugins.httpplugin.MediaTypeWrap
import cc.vv.mvp.activity.BaseActivityMVP
import cc.vv.mvp.binder.BaseDataBinder
import cc.vv.mvp.fragment.BaseFragmentMVP
import com.dawning.utiming.task.bean.FileUrlObj
import com.dawning.utiming.task.inter.SelectedOrDeleteFileInterface
import com.dawning.utiming.task.server.SubmitJobServer
import com.zxy.tiny.Tiny
import com.zxy.tiny.callback.FileWithBitmapCallback

/**
 * 工作签到fragment
 * Created by Chen.qi on 2018/10/27.
 */
class WorkInFragment : BaseFragmentMVP<WorkInFragmentDelegate>()
        , SelectedOrDeleteFileInterface, LookBigPicFileInterface {

    /**
     * 固定占位数据
     */
    private val zwStrData = "zhaWeiShuJu"

    private var whetherRefresh = false
    /**
     * 图片压缩操作
     */
    private var optionsImage: Tiny.FileCompressOptions? = null

    /**
     * 本地数据集合
     */
    private var locationList: ArrayList<FileUrlObj>? = null

    /**
     * 签退本地图片数据
     */
    private var qianTuiPicList: ArrayList<FileUrlObj>? = null


    private var onlyQianDao: ArrayList<String>? = null

    private var onlyQianTui: ArrayList<String>? = null

    /**
     * 判断是否自己
     */
    private var mineMobile: String? = null

    /**
     * 类型
     */
    private var type: Int = 0

    private var cunId: String? = null

    fun setCunId(cunId: String?) {
        this.cunId = cunId
    }

    private var qianDaoId: String? = null

    private var addDetailInterface: AddWorkIdInterface? = null


    fun setAddDetailInter(addDetailInterface: AddWorkIdInterface?) {
        this.addDetailInterface = addDetailInterface
    }


    override fun initView(bundle: Bundle?) {
        super.initView(bundle)
        optionsImage = Tiny.FileCompressOptions()
        locationList = ArrayList()
        qianTuiPicList = ArrayList()

        onlyQianDao = ArrayList()
        onlyQianTui = ArrayList()


        viewDelegate.setSelectedFileInterface_QD(this)
        val obj = FileUrlObj(zwStrData, "")
        locationList!!.add(obj)
        viewDelegate.setSelectedFileObj_QD(locationList)

        viewDelegate.setSelectedFileInterface_QT(this)
        val objQT = FileUrlObj(zwStrData, "")
        qianTuiPicList!!.add(objQT)
        viewDelegate.setSelectedFileObj_QT(qianTuiPicList)
    }


    override fun getData(obj: BaseResponseObj<*>?) {
        super.getData(obj)
        when (obj) {
            is AddQianDaoResponseObj -> {
                //签到、签退成功
                PartyManagerServer.getQianDaoInfo(qianDaoId, "")
            }

            is DiYiShuJiInfoResponseObj -> {
                Log.e("lk_chen", "result==" + "请求成功---------------------");
                val data = obj.data
                mineMobile = data?.mobile
                addDetailInterface?.setMobile(mineMobile)
                viewDelegate?.setHead(data?.faceUrl)
                viewDelegate?.setName(data?.pname)
                viewDelegate?.setPlant(data?.plant)
                viewDelegate?.setPhone(data?.mobile)
                qianDaoId = data?.id
                addDetailInterface?.getDetailId(qianDaoId)
                PartyManagerServer.getQianDaoInfo(qianDaoId, "")
            }

            is QianDaoResponseObj -> {
                Log.e("lk_chen", "result==" + "444444444");
                val data = obj.data
                viewDelegate?.setCurrentTime(data?.time)
                val systemCurrentTime = data?.systemCurrentTime
                Log.e("lk_chen", "result==" + mineMobile);
                val time = data?.time
                if (systemCurrentTime == time && UserInfoManageUtil.isEqualMobile(mineMobile)) {
                    onlyQianDao!!.clear()
                    onlyQianTui!!.clear()
                    locationList!!.clear()
                    val objQD = FileUrlObj(zwStrData, "")
                    locationList!!.add(objQD)
                    qianTuiPicList!!.clear()
                    val objQT = FileUrlObj(zwStrData, "")
                    qianTuiPicList!!.add(objQT)

                    val teamSignInList = data?.teamSignInList
                    if (null == teamSignInList) {
                        //未签到
                        viewDelegate?.showViewQD(0)
                        viewDelegate?.setSelectedFileObj_QD(locationList)

                    } else {
                        val size = teamSignInList.size
                        if (size == 1) {
                            // 已签到还未签退
                            viewDelegate?.showViewQD(1)
                            viewDelegate?.setQianDaotime(teamSignInList[0].signTime)
                            val imageList = teamSignInList[0].imageList
                            if (null != imageList && imageList.size > 0) {
                                for (i in 0 until imageList.size) {
                                    val url = imageList[i]
                                    if (!TextUtils.isEmpty(url)) {
                                        onlyQianDao!!.add(url)
                                    }
                                }
                            }
                            viewDelegate?.onlyShowQianDao(this, onlyQianDao)
                            viewDelegate?.setSelectedFileObj_QT(qianTuiPicList)

                        } else if (size == 2) {
                            // 已签到 已签退
                            viewDelegate?.showViewQD(2)
                            viewDelegate?.setQianDaotime(teamSignInList[0].signTime)
                            viewDelegate?.setQianTuitime(teamSignInList[1].signTime)
                            val imageListQD = teamSignInList[0].imageList
                            if (null != imageListQD && imageListQD.size > 0) {
                                for (i in 0 until imageListQD.size) {
                                    val url = imageListQD[i]
                                    if (!TextUtils.isEmpty(url)) {
                                        onlyQianDao!!.add(url)
                                    }
                                }
                            }
                            viewDelegate?.onlyShowQianDao(this, onlyQianDao)

                            val imageListQT = teamSignInList[1].imageList
                            if (null != imageListQT && imageListQT.size > 0) {
                                for (i in 0 until imageListQT.size) {
                                    val url = imageListQT[i]
                                    if (!TextUtils.isEmpty(url)) {
                                        onlyQianTui!!.add(url)
                                    }
                                }
                            }
                            viewDelegate?.onlyShowQianTui(this, onlyQianTui)

                        }
                    }
                } else {
                    //不能签到，仅展示数据
                    viewDelegate?.showViewQD(2)
                    onlyQianDao!!.clear()
                    onlyQianTui!!.clear()
                    locationList!!.clear()
                    val objQD = FileUrlObj(zwStrData, "")
                    locationList!!.add(objQD)

                    qianTuiPicList!!.clear()
                    val objQT = FileUrlObj(zwStrData, "")
                    qianTuiPicList!!.add(objQT)

                    val teamSignInList = data?.teamSignInList

                    if (null == teamSignInList) {
                        viewDelegate?.setQianDaotime("")
                        viewDelegate?.setQianTuitime("")
                        onlyQianDao!!.add("")
                        onlyQianTui!!.add("")
                        viewDelegate?.onlyShowQianDao(this, onlyQianDao)
                        viewDelegate?.onlyShowQianTui(this, onlyQianTui)
                    } else {
                        val size = teamSignInList.size
                        if (size == 1) {
                            viewDelegate?.setQianDaotime(teamSignInList[0].signTime)
                            val imageList = teamSignInList[0].imageList
                            if (null != imageList && imageList.size > 0) {
                                for (i in 0 until imageList.size) {
                                    val url = imageList[i]
                                    if (!TextUtils.isEmpty(url)) {
                                        onlyQianDao!!.add(url)
                                    }
                                }
                            }
                            viewDelegate?.onlyShowQianDao(this, onlyQianDao)

                        } else if (size == 2) {
                            viewDelegate?.setQianDaotime(teamSignInList[0].signTime)
                            viewDelegate?.setQianTuitime(teamSignInList[1].signTime)
                            val imageListQD = teamSignInList[0].imageList
                            if (null != imageListQD && imageListQD.size > 0) {
                                for (i in 0 until imageListQD.size) {
                                    val url = imageListQD[i]
                                    if (!TextUtils.isEmpty(url)) {
                                        onlyQianDao!!.add(url)
                                    }
                                }
                            }
                            viewDelegate?.onlyShowQianDao(this, onlyQianDao)

                            val imageListQT = teamSignInList[1].imageList
                            if (null != imageListQT && imageListQT.size > 0) {
                                for (i in 0 until imageListQT.size) {
                                    val url = imageListQT[i]
                                    if (!TextUtils.isEmpty(url)) {
                                        onlyQianTui!!.add(url)
                                    }
                                }
                            }
                            viewDelegate?.onlyShowQianTui(this, onlyQianTui)

                        }
                    }


                }
            }

            is FileUpResponseObj -> {
                //头像
                val path = obj.data.url
                uploadServerSuccessImage(path, type)
            }
        }
    }


    override fun initData() {

    }

    override fun onVisibilityChanged(visible: Boolean) {
        super.onVisibilityChanged(visible)
        if (visible && !whetherRefresh) {
            PartyManagerServer.getDiYiShuJiInfo(cunId)
            whetherRefresh = true
        }
    }


    override fun bindEvenListener() {
        viewDelegate?.setOnClickListener(View.OnClickListener {
            //签到时间选择
            ResourceChooseServer.chooseData(activity, handler)

        }, R.id.rl_fwi_timeChoose)


        viewDelegate?.setOnClickListener(View.OnClickListener {
            var isSubmit = false
            val list = ArrayList<String>()
            for (i in 0 until locationList!!.size) {
                if (!TextUtils.isEmpty(locationList!![i].serverUrl)) {
                    isSubmit = true
                    list.add(locationList!![i].serverUrl!!)
                }
            }

            if (!isSubmit) {
                LKToastUtil.showToastShort("请上传图片")
                return@OnClickListener
            }

            val param = AddQianDaoObj()
            param.imgList = list
            param.signType = "0"
            param.teamId = qianDaoId
            BaseHttpRequest.postRequest(PartyManagerAPI.submitQdAndQt,
                    param, AddQianDaoResponseObj::class.java, true,
                    Settings(MediaTypeWrap.MEDIA_TYPE_RAW_JSON))

        }, R.id.tv_fwi_qianDaoConfirm)


        viewDelegate?.setOnClickListener(View.OnClickListener {
            var isSubmit = false
            val list = ArrayList<String>()
            for (i in 0 until qianTuiPicList!!.size) {
                if (!TextUtils.isEmpty(qianTuiPicList!![i].serverUrl)) {
                    isSubmit = true
                    list.add(qianTuiPicList!![i].serverUrl!!)
                }
            }

            if (!isSubmit) {
                LKToastUtil.showToastShort("请上传图片")
                return@OnClickListener
            }

            val param = AddQianDaoObj()
            param.imgList = list
            param.signType = "1"
            param.teamId = qianDaoId
            BaseHttpRequest.postRequest(PartyManagerAPI.submitQdAndQt,
                    param, AddQianDaoResponseObj::class.java, true,
                    Settings(MediaTypeWrap.MEDIA_TYPE_RAW_JSON))

        }, R.id.tv_fwi_qianTuiCancel)


    }

    override fun onHandleMsg(msg: Message?) {
        super.onHandleMsg(msg)
        when (msg?.what) {
            10 -> {
                val dateString: String = msg.obj as String
                viewDelegate?.setCurrentTime(dateString)
                PartyManagerServer.getQianDaoInfo(qianDaoId, dateString)
            }
        }
    }

    override fun getDelegateClass(): Class<WorkInFragmentDelegate> {
        return WorkInFragmentDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return ManagerBaseBinder()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (null == data || resultCode != BaseActivityMVP.RESULT_OK) {
            return
        }
        val imagePath: ArrayList<String>? = data.getStringArrayListExtra(ImageSelector.SELECTED_RESULT)
        if (null != imagePath && imagePath.size > 0) {
            for (i in 0 until imagePath.size) {
                val filePath = imagePath[i]
                compressPic(filePath, optionsImage, this)
            }
        }
    }


    private fun fileUpload(imgUrl: String) {
        val uploadFile = ResourceChooseServer.uploadFile(imgUrl)
        if (null == uploadFile) {
            LKToastUtil.showToastShort("头像上传失败")
            return
        }
        val headPath = JniModuleAPI.uploadHeadHttp
        BaseHttpRequest.postFileRequest(headPath, uploadFile, FileUpResponseObj::class.java, true)
    }


    /**
     * 压缩图片
     */
    private fun compressPic(filePath: String, optionsImage: Tiny.FileCompressOptions?, sInterface: SelectedOrDeleteFileInterface?) {
        Tiny.getInstance().source(filePath).asFile().withOptions(optionsImage)
                .compress(FileWithBitmapCallback { isSuccess, bitmap, outfile, throwable ->
                    if (isSuccess) {
                        fileUpload(outfile)
                    } else {
                        if (TextUtils.isEmpty(filePath)) {
                            return@FileWithBitmapCallback
                        }
                        fileUpload(filePath)
                    }
                })
    }

    override fun lookLargerImage(position: Int, type: Int) {
        val list = ArrayList<String>()
        if (type == 0) {
            for (i in 0 until locationList!!.size) {
                if (zwStrData != locationList!![i].localPath) {
                    list.add(locationList!![i].localPath!!)
                } else {
                    locationList!!.remove(locationList!![i])
                }
            }
        } else if (type == 1) {
            for (i in 0 until qianTuiPicList!!.size) {
                if (zwStrData != qianTuiPicList!![i].localPath) {
                    list.add(qianTuiPicList!![i].localPath!!)
                } else {
                    qianTuiPicList!!.remove(qianTuiPicList!![i])
                }
            }
        }
        SubmitJobServer.largePic(activity, list, position)
    }

    override fun lookBigImage(position: Int, type: Int) {
        if (type == 0) {
            SubmitJobServer.largePic(activity, onlyQianDao!!, position)
        } else if (type == 1) {
            SubmitJobServer.largePic(activity, onlyQianTui!!, position)
        }
    }


    override fun playingVideo(videoPath: String, type: Int) {
        VideoPlayerUtils.getInstance().playVideo(activity, videoPath)
    }

    override fun deleteFile(position: Int, type: Int) {
        if (type == 0) {
            val strRemove = locationList!![position]
            SubmitJobServer.delKey = strRemove.serverUrl
            locationList!!.remove(strRemove)
            val fileNormal = FileUrlObj(zwStrData, "")
            locationList!!.remove(fileNormal)
            locationList!!.add(fileNormal)
            viewDelegate?.setSelectedFileObj_QD(locationList)

        } else if (type == 1) {
            val strRemove = qianTuiPicList!![position]
            SubmitJobServer.delKey = strRemove.serverUrl
            qianTuiPicList!!.remove(strRemove)
            val fileNormal = FileUrlObj(zwStrData, "")
            qianTuiPicList!!.remove(fileNormal)
            qianTuiPicList!!.add(fileNormal)
            viewDelegate?.setSelectedFileObj_QT(qianTuiPicList)
        }

    }

    override fun continueSelectedFile(type: Int) {
        //传递已选择的文件
        this.type = type

        if (type == 0) {
            val fileNormal = FileUrlObj(zwStrData, "")
            locationList!!.remove(fileNormal)
            SubmitJobServer.openPic(activity, this, 6 - locationList!!.size)
            if (locationList!!.size < 6) {
                locationList!!.add(fileNormal)
            }

        } else if (type == 1) {
            val fileNormal = FileUrlObj(zwStrData, "")
            qianTuiPicList!!.remove(fileNormal)
            SubmitJobServer.openPic(activity, this, 6 - qianTuiPicList!!.size)
            if (qianTuiPicList!!.size < 6) {
                qianTuiPicList!!.add(fileNormal)
            }
        }
    }


    override fun getBadCode(obj: BaseResponseObj<*>?) {
        super.getBadCode(obj)
    }

    override fun onHttpFailure(url: String?, exceptionStr: String?) {
        super.onHttpFailure(url, exceptionStr)
        if (JniModuleAPI.uploadHeadHttp == url) {
            LKToastUtil.showToastShort("图片上传失败，请重试")
        }
    }


    override fun uploadServerSuccessImage(filePath: String, type: Int) {
        if (type == 0) {
            val fileObj = FileUrlObj(filePath, filePath)
            locationList!!.add(fileObj)

            val fileNormal = FileUrlObj(zwStrData, "")
            if (locationList!!.size <= 6) {
                locationList!!.remove(fileNormal)
                locationList!!.add(fileNormal)
            } else {
                locationList!!.remove(fileNormal)
            }
            viewDelegate?.setSelectedFileObj_QD(locationList)


        } else if (type == 1) {
            val fileObj = FileUrlObj(filePath, filePath)
            qianTuiPicList!!.add(fileObj)

            val fileNormal = FileUrlObj(zwStrData, "")
            if (qianTuiPicList!!.size <= 6) {
                qianTuiPicList!!.remove(fileNormal)
                qianTuiPicList!!.add(fileNormal)
            } else {
                qianTuiPicList!!.remove(fileNormal)
            }
            viewDelegate?.setSelectedFileObj_QT(qianTuiPicList)
        }
    }

    override fun uploadServerFailPic(filePath: String, type: Int) {

    }
}